package com.sitech.sso;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sitech.BaseConst;
import com.sitech.context.SpringContext;
import com.sitech.portal.system.domain.TblSYS_LOGINMSG;
import com.sitech.portal.system.domain.TblSYS_USER_ROLE;
import com.sitech.portal.system.service.IPublicSysService;
import com.sitech.portal.system.service.ISysDeptService;
import com.sitech.portal.system.service.ISysLogInmsgService;
import com.sitech.portal.system.service.ISysParaService;
import com.sitech.portal.system.service.ISysRoleService;
import com.sitech.portal.system.service.ISysStyleService;

/**
 * 获取用户信息并写入到session中，配合CAS单点登录客户端一起使用
 * @modify fanxf
 */
public class SSOFilter implements Filter
{
	public Log log = LogFactory.getLog(this.getClass());

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException
	{
			HttpServletRequest httpRequest = (HttpServletRequest) request;
			HttpServletResponse httpResponse = (HttpServletResponse) response;

			// TODO 获取用户名，由单点登录服务返回给门户
			/**
			 * 从session中取出主账号 或者从账号和密码放入userCode, userPassword中
			 */

			String userCode = (String) httpRequest.getSession().getAttribute(System.getProperty(BaseConst.SSO_USER_SESSION_PATH));
			TblSYS_LOGINMSG user = (TblSYS_LOGINMSG) httpRequest.getSession().getAttribute(BaseConst.SESSION_USER_KEY);
            if (httpRequest.getParameter("Token") != null) {//获取4a主账号存到session,以便保存访问日志时使用
                String token = httpRequest.getParameter("Token").toString();
                String tokens[] = new String[]{};
                if (!"".equals(token)) {
                    tokens = token.split("@");
                    if (tokens.length > 3) {
                        String MASTER_ID = tokens[3];
                        httpRequest.getSession().setAttribute(BaseConst.SESSION_MASTER_USER_KEY, MASTER_ID);
                    }
                }
            }
			try {
				// 如果session中用户信息为空，则去数据库中取用户信息。
				if (user == null) {
					if(userCode==null){
						chain.doFilter(httpRequest, httpResponse);
						return;
					}
					
					user = new TblSYS_LOGINMSG();
					String userPassword = "";
					HashMap map = null;
					IPublicSysService publicSysService = (IPublicSysService) SpringContext.getBean("publicSysService");
					String[] tablenames = { "TB_SYS_MANAGE_UNIT",
							"TB_SYS_USER_PRIVILEGE" };
					int tableCount = publicSysService.findUserTable(tablenames);
					// 获得用户的界面风格设置信息
					ISysStyleService sysStyleService = (ISysStyleService) SpringContext.getBean("sysStyleService");
					ISysParaService sysParaService = (ISysParaService) SpringContext.getBean("sysParaService");
					String DEFAULT_STYLE_PATH = sysParaService.findSysParaByParaId(
							"STYLE_PATH").get("PARA_VALUE").toString();
					String stylePath = sysStyleService.getSYSStylePath(null);
					if (stylePath == null || "".equals(stylePath)
							|| "null".equals(stylePath)) {
						stylePath = DEFAULT_STYLE_PATH;
					}

					String STYLE_IS_TAB = sysStyleService.getIsTab(null);
					if (STYLE_IS_TAB == null || "".equals(STYLE_IS_TAB)
							|| "null".equals(STYLE_IS_TAB)) {
						STYLE_IS_TAB = "0";
					}
					user.setSTYLE_IS_TAB(STYLE_IS_TAB);

					ISysLogInmsgService sysLogInmsgService = (ISysLogInmsgService) SpringContext.getBean("sysLogInmsgService");
					map = sysLogInmsgService.validLoginBySSO(userCode, userPassword, tableCount);

//					user.setCOMP_ID((String) map.get("COMP_ID"));
					user.setDEPT_ID((String) map.get("DEPT_ID"));
					user.setLOGIN_ID((String) map.get("LOGIN_ID"));
					user.setLOGIN_PASSWD((String) map.get("LOGIN_PASSWD"));

//					String unit_idStr = "ALL";
					// 判断用户是否有其他管理单元的特权
//					if (tableCount == 2) {
//						ISysUserPrivilegeService sysUserPrivilegeService = (ISysUserPrivilegeService) SpringContext.getBean("sysUserPrivilegeService");
//						unit_idStr = sysUserPrivilegeService.getUserPrivilegeStrByLogin_id((String) map.get("LOGIN_ID"));
//						unit_idStr += (String) map.get("UNIT_ID") == null ? "" : (String) map.get("UNIT_ID");
//
//						// 判断是否有管理单元没有则设置为所有权限
//						if (unit_idStr != null && !"".equals(unit_idStr)) {
//							user.setMANAGE_UNIT_ID(unit_idStr);
//						} else {
//							user.setMANAGE_UNIT_ID("ALL");
//						}
//					} else {
//						user.setMANAGE_UNIT_ID("ALL");
//					}

					// user.setMANAGE_UNIT_ID("ALL");
					user.setLOGIN_PHONE((String) map.get("LOGIN_PHONE"));
					user.setLOCAL_PHONE((String) map.get("LOCAL_PHONE"));
					user.setNAME((String) map.get("NAME"));
					user.setLOGIN_STATE(Integer.parseInt(map.get("LOGIN_STATE").toString()));
					user.setEMAIL_ADDR((String) map.get("EMAIL_ADDR"));
					user.setLOCKSTATE((String) map.get("LOCKSTATE"));
					user.setStylePath(stylePath);
					user.setMENU_TYPE(map.get("MENU_TYPE")==null?"2":(String) map.get("MENU_TYPE"));
                    // 用户拥有的角色
					ISysRoleService sysRoleService = (ISysRoleService) SpringContext.getBean("sysRoleService");
                    TblSYS_USER_ROLE rol = new TblSYS_USER_ROLE();
                    rol.setLOGIN_ID(user.getLOGIN_ID());
                    user.setRoles(sysRoleService.findForRoleListByLonginId(rol));
                    
                    //用户管理的部门
                    ISysDeptService sysDeptService = (ISysDeptService) SpringContext.getBean("sysDeptService");
                    List<HashMap> deptList = sysDeptService.findDeptByMgrId(user.getLOGIN_ID());
                    user.setMgrDepts(deptList);

                    HttpSession session = httpRequest.getSession();
                    session.setAttribute(BaseConst.SESSION_USER_KEY, user);
					Map sessions = (Map) session.getServletContext().getAttribute("sessions");
					if (sessions == null) {
						sessions = new HashMap();
						httpRequest.setAttribute("sessions", sessions);
					}
					sessions.put(user.getLOGIN_ID(),session);
				}
				chain.doFilter(httpRequest, httpResponse);
			} catch (Exception sex) {
				log.info(sex);
				sex.printStackTrace();
				httpResponse.setHeader("Charset", "GB2312");
				httpResponse.setContentType("text/html;charset=gb2312");
				httpResponse.setHeader("Cache-Control", "no-cache");
				httpResponse.getWriter().write(sex.getMessage());
			}
	}

	public void destroy()
	{

	}

	public void init(FilterConfig arg0) throws ServletException
	{

	}
}
